package com.thorqq.wuxibusgui;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

import com.alibaba.fastjson.JSON;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Net
{
    public static OkHttpClient mHttpClient = new OkHttpClient.Builder()
        .readTimeout(Constants.READ_TIMEOUT,TimeUnit.SECONDS)//设置读取超时时间
        .writeTimeout(Constants.WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间
        .connectTimeout(Constants.CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间
        .build();

    public static String request(Object pkg)
    {
        //设置　nonce :　UUID
        Field[] fields = pkg.getClass().getDeclaredFields();  
        for(Field f : fields)
        {
            if(f.getType().toString().equalsIgnoreCase("class java.lang.String")
                    && f.getName().equalsIgnoreCase("nonce"))
            {
                try
                {
                    f.set(pkg, Utils.getRandomUUID());
                    break;
                }
                catch(Exception ex)
                {
                    Log.ex(ex);
                }
            }
        }
        
        String jsonString = JSON.toJSONString(pkg);
        Log.d("Request: " + jsonString);
       
        byte[] aesString = Utils.AESEncode(jsonString.getBytes());

        String base64String = Utils.Base64Encode(aesString);

        return Net.request(base64String);
    }
    
    public static String request(String b)
    {
        RequestBody body = new FormBody.Builder()
                .add("b", b) // OkHttp会自动对base64String做URLEncode
                .add("a", "Android").build();

        Request request = new Request.Builder().url("http://api.wxbus.com.cn/api/")
                // .header("User-Agent", "Dalvik/1.6.0 (Linux; U; Android 4.4.4; S3 Build/KTU84P)")
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
                .addHeader("Charset", "UTF-8")
                // .addHeader("Connection", "Keep-Alive")
                .addHeader("Accept-Encoding", "gzip")
                // .addHeader("Host", "api.wxbus.com.cn")
                .post(body).build();

        Response response = null;
        try
        {
            response = mHttpClient.newCall(request).execute();

            byte[] responseBody = response.body().bytes();
            if (responseBody.length == 0)
            {
                Log.e(response.toString());
                return null;
            }

            ByteArrayInputStream paramArrayOfByte = new ByteArrayInputStream(responseBody);
            GZIPInputStream gin = new GZIPInputStream(paramArrayOfByte);
            BufferedReader in2 = new BufferedReader(new InputStreamReader(gin, "UTF-8"));
            StringBuffer buf = new StringBuffer();
            String s = null;
            // 读取压缩文件里的内容
            while ((s = in2.readLine()) != null)
            {
                buf.append(s);
            }
            in2.close();

            String result = buf.toString();
            Log.d("Response: " + result);
            return result;

        }
        catch (Exception e)
        {
            Log.ex(e);
            e.printStackTrace();
        }
        
        return null;
    }
}